package com.gopay.scheduler;

import org.quartz.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by liyang on 2017/5/8.
 */
public class GopayJobCronFactory extends SchedulerFactoryBean implements ApplicationContextAware {


    private ApplicationContext applicationContext;

    @Resource(name = "cronTriggerMap")
    private Map<String,List<CronTriggerBean>> cronTriggerMap;

    private boolean switchJOBCRON;

    public void init() throws SchedulerException {

        logger.error("------------初始化quartz监控任务 start-------------");

        List<Trigger> triggerList=new ArrayList<Trigger>();
        if(switchJOBCRON){
            triggerList.addAll(cronTriggerMap.get("JOB_CRON"));
            logger.error("--switchREALTIME="+switchJOBCRON);
        }
        String jobDetailName;
        JobDetail jobDetail;
        for(Trigger trigger:triggerList){
            jobDetailName=trigger.getJobKey().getName();
            logger.error("********jobDetailName="+jobDetailName);
            jobDetail=(JobDetail)applicationContext.getBean(jobDetailName);
            this.getScheduler().scheduleJob(jobDetail, trigger);
        }

        this.getScheduler().start();
    }

    public void setSwitchJOBCRON(boolean switchJOBCRON) {
        this.switchJOBCRON = switchJOBCRON;
    }

    public boolean getSwitchJOBCRON() {
        return switchJOBCRON;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}
